package util

import (
	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"io"
	"os"
)

var (
	logger  *zap.Logger
	encoder zapcore.Encoder
)

const (
	Running = iota
	Errors
)

// InitZap 初始化zap编码，输出格式定为json格式可以做数据分析
func InitZap() {
	encoder = zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig())
}

// GetLogger status可以是Running或者Errors，分别返回运行日志或错误日志
func GetLogger(status int) (*zap.SugaredLogger, error) {
	setting, err := lumberjackSetting(status)
	if err != nil {
		panic(err)
	}
	logger = zap.New(zapcore.NewCore(encoder, setting, zapcore.DebugLevel))
	return logger.Sugar(), nil
}

// lumberjackSetting  开启日志归档设置
func lumberjackSetting(status int) (zapcore.WriteSyncer, error) {
	var file string
	switch status {
	case Running:
		file = ZapSetting.RunningFilename
	case Errors:
		file = ZapSetting.ErrorsFilename
	default:
		return nil, ZapNotFoundFileError
	}
	llogger := &lumberjack.Logger{
		Filename:   file,
		MaxSize:    ZapSetting.FileSize,
		MaxBackups: ZapSetting.OldFileNumbers,
		MaxAge:     ZapSetting.MaxAge,
		Compress:   false,
	}
	return zapcore.AddSync(io.MultiWriter(llogger, os.Stdout)), nil
}
